/**

 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 *
 * 项目名：cards-web 
 * 文件名：:StatementOrderSyncListener.java
 * 模块说明：	
 * 修改历史：
 * 2017年9月18日 - liyang - 创建。
 *
 */
package com.thor.palmmall.rest.event.listener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.xml.rpc.ServiceException;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.eventbus.Subscribe;
import com.thor.commons.entity.Operator;
import com.thor.commons.entity.UCN;
import com.thor.commons.util.StringUtil;
import com.thor.palmmall.api.statement.AStatementPayBill;
import com.thor.palmmall.api.statement.AStatementPayBillDetail;
import com.thor.palmmall.api.statement.AStatementPayBillState;
import com.thor.palmmall.api.statement.StatementService;
import com.thor.palmmall.rest.event.StatementOrderSyncEvent;
import com.thor.palmmall.spi.common.SResponse;
import com.thor.palmmall.spi.payment.SPaymentBill;
import com.thor.palmmall.spi.payment.SPaymentService;
import com.thor.palmmall.spi.payment.SStatementPayParam;
import com.thor.palmmall.spi.payment.SStatementPayParam.Lines;
import com.thor.palmmall.util.event.Event;
import com.thor.palmmall.util.event.EventHandler;
import com.thor.palmmall.util.event.GlobalEventBus;

/**
 * @author:liyang
 * @time:2017年9月18日 上午11:41:27
 * @since:1.0
 */
public class StatementOrderSyncListener implements EventHandler {

  @Autowired
  private StatementService statementService;

  @Autowired
  private SPaymentService paymentService;

  @PostConstruct
  public void init() {
    GlobalEventBus.register(this);
  }

  @Override
  @Subscribe
  public void process(Event event) throws Exception {
    if (!(event instanceof StatementOrderSyncEvent)) {
      return;
    }
    AStatementPayBill bill = ((StatementOrderSyncEvent) event).getBill();

    if (bill == null) {
      return;
    }

    try {
      SResponse<SPaymentBill> sp = syncBill2Hd(bill);
      if (sp.isSuccess()) {
        // 重查数据库，防止乐观锁检查版本抛出异常
        AStatementPayBill aBill = statementService.getByBillNumber(bill.getBillNumber());
        aBill.setBillId((null == sp.getBody()) ? null : sp.getBody().getBillNumber());
        aBill.setActionTime(new Date());
        aBill.setState(AStatementPayBillState.FINISH);
        aBill.setTryCount(aBill.getTryCount() + 1);
        statementService.saveStatementPayBill(aBill, aBill.getCreateInfo());
      } else {
        AStatementPayBill aBill = statementService.getByBillNumber(bill.getBillNumber());
        aBill.setTryCount(aBill.getTryCount() + 1);
        aBill.setSyncedErrorMsg(sp.getMessage());
        statementService.saveStatementPayBill(aBill, aBill.getCreateInfo());
      }
    } catch (ServiceException e) {
      e.printStackTrace();
    }
  }

  private SResponse<SPaymentBill> syncBill2Hd(AStatementPayBill bill) throws ServiceException {
    if (bill == null || bill.getDetails() == null) {
      throw new ServiceException("订单或订单明细为空");
    }

    List<Lines> lines = new ArrayList<Lines>();
    for (AStatementPayBillDetail detail : bill.getDetails()) {
      Lines line = new Lines();
      line.setAccId(detail.getAccId());
      line.setTotal(detail.getUnpayedTotal());
      line.setPaymentType(bill.getPaymentType());
      line.setBankCode(detail.getBankCode());
      line.setPoundage(detail.getPoundage());
      lines.add(line);
    }

    Operator operator = bill.getCreateInfo().getOperator();
    SStatementPayParam param = new SStatementPayParam();
    param.setDealer(new UCN(operator.getId(), operator.getId(), operator.getOperName()));
    param.setDirection(1);
    param.setPaymentDate(StringUtil.dateToString(bill.getActionTime(), "yyyy.MM.dd HH:mm:ss"));
    param.setLines(lines);
    param.setRemark(bill.getRemark());
    return paymentService.pay(param);
  }
}
